<?php
/**
 * 违规记录展示页面
 * 功能：展示和管理考试项目的违规记录
 * 权限：仅考试项目管理员可访问
 */

// 开启会话
session_start();

// 错误报告设置
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 检查用户是否已登录
if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
    header('Location: index.php');
    exit();
}

// 为navigation.php设置必需变量
$current_user_id = $_SESSION['user_id'] ?? '';
$GLOBALS['current_user_id'] = $current_user_id;

// 数据库连接
try {
    if (!file_exists('database.php')) {
        throw new Exception("database.php文件不存在");
    }

    require_once 'database.php';

    if (!isset($conn) || !($conn instanceof mysqli)) {
        throw new Exception("数据库连接失败");
    }

    if (!$conn->ping()) {
        throw new Exception("数据库连接已断开");
    }

} catch (Exception $e) {
    $_SESSION['error_message'] = "数据库连接失败：" . $e->getMessage();
    header('Location: user_home.php');
    exit();
}

// 包含统一导航栏
if (file_exists('common/navigation.php')) {
    require_once 'common/navigation.php';
}

// 如果getUserRoles函数不存在，定义备用函数
if (!function_exists('getUserRoles')) {
    function getUserRoles($user_id, $conn) {
        $roles = [];
        try {
            $sql = "SELECT role FROM user_roles WHERE user_id = ?";
            $stmt = $conn->prepare($sql);

            if ($stmt) {
                $stmt->bind_param("s", $user_id);
                $stmt->execute();
                $result = $stmt->get_result();

                while ($row = $result->fetch_assoc()) {
                    $roles[] = $row['role'];
                }
                $stmt->close();
            }
        } catch (Exception $e) {
            error_log("获取用户角色失败: " . $e->getMessage());
        }

        return $roles;
    }
}

// 权限验证 - 仅考试项目管理员可访问
$user_roles = getUserRoles($current_user_id, $conn);
if (!in_array('考试项目管理员', $user_roles)) {
    $_SESSION['error_message'] = "访问被拒绝：您需要考试项目管理员权限才能访问此页面";
    header('Location: access_denied.php');
    exit();
}

// 获取考试项目ID
$exam_id = intval($_GET['exam_id'] ?? 0);
if ($exam_id <= 0) {
    $_SESSION['error_message'] = "无效的考试项目ID";
    header('Location: exam_projects.php');
    exit();
}

// 初始化变量
$exam = null;
$violations = [];
$error_message = '';
$success_message = $_SESSION['success_message'] ?? '';
unset($_SESSION['success_message']);

// 获取考试项目信息
try {
    $exam_sql = "SELECT * FROM exams WHERE id = ? AND status = 'active'";
    $exam_stmt = $conn->prepare($exam_sql);

    if (!$exam_stmt) {
        throw new Exception("准备查询语句失败: " . $conn->error);
    }

    $exam_stmt->bind_param("i", $exam_id);
    $exam_stmt->execute();
    $result = $exam_stmt->get_result();

    if ($result->num_rows === 0) {
        throw new Exception("考试项目不存在或已被删除");
    }

    $exam = $result->fetch_assoc();
    $exam_stmt->close();

} catch (Exception $e) {
    $error_message = $e->getMessage();
    $_SESSION['error_message'] = $error_message;
    header('Location: exam_projects.php');
    exit();
}

// 获取违规记录列表
try {
    $violations_sql = "SELECT * FROM violations WHERE exam_id = ? ORDER BY violation_date DESC, created_at DESC";
    $violations_stmt = $conn->prepare($violations_sql);

    if (!$violations_stmt) {
        throw new Exception("准备查询违规记录失败: " . $conn->error);
    }

    $violations_stmt->bind_param("i", $exam_id);
    $violations_stmt->execute();
    $violations_result = $violations_stmt->get_result();

    while ($row = $violations_result->fetch_assoc()) {
        $violations[] = $row;
    }

    $violations_stmt->close();

} catch (Exception $e) {
    $error_message = "获取违规记录失败: " . $e->getMessage();
}

$page_title = '违规记录展示 - 考务管理系统';
?>

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title><?php echo htmlspecialchars($page_title); ?></title>

        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
        <!-- Font Awesome -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

        <style>
            .main-content {
                margin-top: 20px;
                padding-bottom: 40px;
            }

            .page-header {
                background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
                color: white;
                padding: 30px;
                border-radius: 10px;
                margin-bottom: 30px;
                text-align: center;
            }

            .info-card {
                background: white;
                border-radius: 10px;
                box-shadow: 0 4px 6px rgba(0,0,0,0.1);
                padding: 25px;
                margin-bottom: 30px;
            }

            .violations-container {
                background: white;
                border-radius: 10px;
                box-shadow: 0 4px 6px rgba(0,0,0,0.1);
                padding: 30px;
            }

            .violations-table {
                margin-top: 20px;
            }

            .severity-badge {
                display: inline-block;
                padding: 6px 12px;
                border-radius: 20px;
                font-size: 12px;
                font-weight: 600;
                text-align: center;
                min-width: 80px;
            }

            .severity-轻微 {
                background-color: #d1ecf1;
                color: #0c5460;
                border: 1px solid #bee5eb;
            }
            .severity-一般 {
                background-color: #fff3cd;
                color: #856404;
                border: 1px solid #ffeaa7;
            }
            .severity-严重 {
                background-color: #f8d7da;
                color: #721c24;
                border: 1px solid #f5c6cb;
            }
            .severity-极严重 {
                background-color: #d4edda;
                color: #155724;
                border: 1px solid #c3e6cb;
                background: linear-gradient(135deg, #dc3545, #c82333);
                color: white;
            }

            .status-badge {
                display: inline-block;
                padding: 4px 10px;
                border-radius: 15px;
                font-size: 11px;
                font-weight: 600;
            }

            .status-待处理 { background-color: #fff3cd; color: #856404; }
            .status-已处理 { background-color: #d4edda; color: #155724; }
            .status-已撤销 { background-color: #f8d7da; color: #721c24; }

            .btn-danger {
                background: linear-gradient(135deg, #dc3545, #c82333);
                border: none;
                padding: 12px 25px;
                font-weight: 600;
            }

            .btn-danger:hover {
                background: linear-gradient(135deg, #c82333, #bd2130);
                transform: translateY(-1px);
            }

            .stats-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
                gap: 20px;
                margin-bottom: 30px;
            }

            .stat-card {
                background: linear-gradient(135deg, #f8f9fa, #e9ecef);
                border-radius: 10px;
                padding: 20px;
                text-align: center;
            }

            .stat-number {
                font-size: 2rem;
                font-weight: 700;
                margin-bottom: 5px;
            }

            .stat-label {
                font-size: 14px;
                color: #6c757d;
                font-weight: 500;
            }

            .stat-轻微 .stat-number { color: #17a2b8; }
            .stat-一般 .stat-number { color: #ffc107; }
            .stat-严重 .stat-number { color: #fd7e14; }
            .stat-极严重 .stat-number { color: #dc3545; }
            .stat-total .stat-number { color: #6c757d; }

            .empty-state {
                text-align: center;
                padding: 60px 20px;
                color: #6c757d;
            }

            .empty-state i {
                font-size: 4rem;
                margin-bottom: 20px;
                opacity: 0.5;
            }

            .table-responsive {
                border-radius: 10px;
                overflow: hidden;
                box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            }

            .table th {
                background-color: #f8f9fa;
                border-bottom: 2px solid #dee2e6;
                font-weight: 600;
                color: #495057;
            }

            .table td {
                vertical-align: middle;
            }

            .violation-description {
                max-width: 200px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }

            .violation-description:hover {
                white-space: normal;
                overflow: visible;
            }

            @media (max-width: 768px) {
                .violations-container {
                    padding: 20px;
                }

                .stats-grid {
                    grid-template-columns: repeat(2, 1fr);
                }

                .table-responsive {
                    font-size: 14px;
                }

                .violation-description {
                    max-width: 100px;
                }
            }
        </style>
    </head>
    <body>
    <!-- 统一导航栏 -->
    <?php include_once 'common/navigation.php'; ?>

    <!-- 主要内容 -->
    <div class="container main-content">
        <!-- 页面标题 -->
        <div class="page-header">
            <h1 class="mb-2">
                <i class="fas fa-exclamation-triangle"></i> 违规记录展示
            </h1>
            <p class="mb-0">查看和管理考试项目的违规记录</p>
        </div>

        <!-- 考试项目信息 -->
        <div class="info-card">
            <h5 class="mb-3"><i class="fas fa-info-circle text-info"></i> 考试项目信息</h5>
            <div class="row">
                <div class="col-md-8">
                    <h4 class="text-primary"><?php echo htmlspecialchars($exam['exam_name']); ?></h4>
                </div>
                <div class="col-md-4 text-end">
                    <a href="add_violation.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-danger">
                        <i class="fas fa-plus"></i> 新建违规记录
                    </a>
                </div>
            </div>
            <div class="row mt-3">
                <div class="col-md-6">
                    <p><strong>考试日期：</strong><?php echo htmlspecialchars($exam['exam_date']); ?></p>
                    <p><strong>结束日期：</strong><?php echo htmlspecialchars($exam['end_date'] ?? '未设置'); ?></p>
                </div>
                <div class="col-md-6">
                    <p><strong>科目数量：</strong><?php echo intval($exam['subject_count']); ?> 门</p>
                    <p><strong>创建者：</strong><?php echo htmlspecialchars($exam['created_by']); ?></p>
                </div>
            </div>
        </div>

        <!-- 成功消息 -->
        <?php if (!empty($success_message)): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success_message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- 错误消息 -->
        <?php if (!empty($error_message)): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="fas fa-exclamation-triangle"></i> <?php echo htmlspecialchars($error_message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- 统计信息 -->
        <?php
        $stats = [
            'total' => count($violations),
            '轻微' => 0,
            '一般' => 0,
            '严重' => 0,
            '极严重' => 0
        ];

        foreach ($violations as $violation) {
            $severity = $violation['severity_level'];
            if (isset($stats[$severity])) {
                $stats[$severity]++;
            }
        }
        ?>

        <div class="stats-grid">
            <div class="stat-card stat-total">
                <div class="stat-number"><?php echo $stats['total']; ?></div>
                <div class="stat-label">总违规记录</div>
            </div>
            <div class="stat-card stat-轻微">
                <div class="stat-number"><?php echo $stats['轻微']; ?></div>
                <div class="stat-label">轻微违规</div>
            </div>
            <div class="stat-card stat-一般">
                <div class="stat-number"><?php echo $stats['一般']; ?></div>
                <div class="stat-label">一般违规</div>
            </div>
            <div class="stat-card stat-严重">
                <div class="stat-number"><?php echo $stats['严重']; ?></div>
                <div class="stat-label">严重违规</div>
            </div>
            <div class="stat-card stat-极严重">
                <div class="stat-number"><?php echo $stats['极严重']; ?></div>
                <div class="stat-label">极严重违规</div>
            </div>
        </div>

        <!-- 违规记录列表 -->
        <div class="violations-container">
            <h5 class="mb-3">
                <i class="fas fa-list"></i> 违规记录列表
                <span class="badge bg-secondary"><?php echo count($violations); ?> 条记录</span>
            </h5>

            <?php if (empty($violations)): ?>
                <!-- 空状态 -->
                <div class="empty-state">
                    <i class="fas fa-clipboard-check"></i>
                    <h4>暂无违规记录</h4>
                    <p class="mb-3">该考试项目还没有违规记录</p>
                    <a href="add_violation.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-danger">
                        <i class="fas fa-plus"></i> 新建违规记录
                    </a>
                </div>
            <?php else: ?>
                <!-- 违规记录表格 -->
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead>
                        <tr>
                            <th>违规日期</th>
                            <th>监考员</th>
                            <th>考试场次</th>
                            <th>违规类型</th>
                            <th>严重程度</th>
                            <th>违反纪律积分</th>
                            <th>状态</th>
                            <th>违规描述</th>
                            <th>记录时间</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($violations as $violation): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($violation['violation_date']); ?></td>
                                <td>
                                    <strong><?php echo htmlspecialchars($violation['invigilator_name']); ?></strong><br>
                                    <small class="text-muted"><?php echo htmlspecialchars($violation['invigilator_id']); ?></small>
                                </td>
                                <td><?php echo htmlspecialchars($violation['exam_session'] ?? '未设置'); ?></td>
                                <td>
                                        <span class="badge bg-warning text-dark">
                                            <?php echo htmlspecialchars($violation['violation_type']); ?>
                                        </span>
                                </td>
                                <td>
                                        <span class="severity-badge severity-<?php echo $violation['severity_level']; ?>">
                                            <?php echo htmlspecialchars($violation['severity_level']); ?>
                                        </span>
                                </td>
                                <td>
                                    <span class="badge bg-danger">
                                        <?php echo number_format($violation['disciplinary_violation_points'] ?? 0, 1); ?> 分
                                    </span>
                                </td>
                                <td>
                                        <span class="status-badge status-<?php echo $violation['status']; ?>">
                                            <?php echo htmlspecialchars($violation['status']); ?>
                                        </span>
                                </td>
                                <td>
                                    <div class="violation-description" title="<?php echo htmlspecialchars($violation['description'] ?? ''); ?>">
                                        <?php echo htmlspecialchars($violation['description'] ?? '无描述'); ?>
                                    </div>
                                </td>
                                <td>
                                    <small><?php echo date('Y-m-d H:i', strtotime($violation['created_at'])); ?></small>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

        <!-- 返回按钮 -->
        <div class="text-center mt-4">
            <a href="exam_projects.php" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> 返回项目列表
            </a>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    </body>
    </html>

<?php
// 关闭数据库连接
if (isset($conn) && $conn instanceof mysqli) {
    $conn->close();
}
?>